<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item>餐券管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card filter">
      <a-spin :spinning="sending">
        <a-form>
          <a-row>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="订餐人" v-bind="formItemLayout">
                <a-input v-model="queryParam.createdByName" allow-clear placeholder="全部" />
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="订单日期" v-bind="formItemLayout">
                <a-week-picker v-model="tempDate" format="YYYY-MM-DD" :allow-clear="false" @change="onWeekChange" />
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="餐券编号" v-bind="formItemLayout">
                <a-input v-model="queryParam.code" allow-clear placeholder="全部" />
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="餐券时间" v-bind="formItemLayout">
                <a-select v-model="queryParam.typeId" allow-clear placeholder="全部">
                  <a-select-option v-for="item in mealType" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <a-form-item label="餐券状态" v-bind="formItemLayout">
                <a-select v-model="tempStatus" allow-clear placeholder="全部">
                  <a-select-option v-for="item in statusList" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :lg="8" :md="12" :sm="24">
              <div class="btn-container align-right">
                <a-button type="primary" @click="handleSearch">查询</a-button>
                <a-button @click="reset">重置</a-button>
                <a-button type="primary" @click="clickExport">导出报表</a-button>
              </div>
            </a-col>
          </a-row>
        </a-form>

        <div class="date-section">
          <div
            v-for="item in dateSection"
            :key="item"
            :class="$moment(selectedDay).format('YYYY-MM-DD') === item ? 'active' : ''"
            @click="changeDate(item)"
          >
            <div style="font-weight:bold;font-size:16px;">
              <span>{{ $moment(item).format('MM-DD') }}</span>
              <span style="margin-left:5px;">{{ $moment(item).format('ddd') }}</span>
            </div>
            <span v-if="$moment(today).isSame(item)" style="font-size:16px;color:#1890ff">今天</span>
          </div>
          <div>
            <router-link :to="`count/${dateSection[0]},${dateSection[dateSection.length - 1]}`">
              <a-icon type="bar-chart" />
              <div>总体统计</div>
            </router-link>
          </div>
        </div>
        <s-table
          ref="manageTable"
          bordered
          class="s-table"
          row-key="id"
          :locale="{ emptyText: '暂无数据' }"
          :show-pagination="false"
          :columns="columns"
          :data="loadData"
          :alert="false"
        >
          <template slot="action" slot-scope="item">
            <div class="action-container">
              <span class="success-link" @click="showMealDetail(item)">详情</span>
              <span v-if="/3|6/.test(item.status)">
                <a-dropdown>
                  <a-menu slot="overlay">
                    <a-menu-item @click="changeStatus({ item, bool: true })">通过</a-menu-item>
                    <a-menu-item class="danger-link" @click="changeStatus({ item, bool: false })">拒绝</a-menu-item>
                  </a-menu>
                  <span class="primary-link">选择操作</span>
                </a-dropdown>
              </span>
            </div>
          </template>
        </s-table>
        <!-- 分页器 -->
        <div class="pagination-container">
          <a-pagination
            :page-size="queryParam.pageSize"
            :show-total="total => `共 ${total} 条记录 第 ${queryParam.pageNum} / ${Math.ceil(total / queryParam.pageSize)} 页`"
            :current="queryParam.pageNum"
            :total="manageCount"
            show-quick-jumper
            hide-on-single-page
            @change="handlePage"
          />
        </div>
      </a-spin>
    </a-card>

    <a-modal
      title="餐券详情"
      :footer="null"
      :visible="showDetail"
      mask-closable
      centered
      width="600px"
      @cancel="showDetail=false"
    >
      <div class="item">订餐人: <span>{{ $get(detailInfo, 'createdByName', '暂无') }}</span></div>
      <div v-if="!/换餐/.test(detailInfo.statusName)" class="item">餐券日期:<span>{{ $get(detailInfo, 'scheduleDate', '暂无') || '暂无' }}</span></div>
      <div v-if="/换餐/.test(detailInfo.statusName)" class="item">原餐券日期:<span>{{ $get(detailInfo, 'lastScheduleDate', '暂无') || '暂无' }}</span></div>
      <div v-if="/换餐/.test(detailInfo.statusName)" class="item">现餐券日期:<span>{{ $get(detailInfo, 'scheduleDate', '暂无') || '暂无' }}</span></div>
      <div class="item">餐券时间:<span>{{ detailInfo.typeName || '暂无' }}</span></div>
      <div class="item">餐券类型:<span>{{ detailInfo.typeString || '暂无' }}</span></div>
      <div v-if="/公务餐/.test(detailInfo.typeString)" class="item">餐券数量:<span>{{ detailInfo.personQty || 0 }}</span></div>
      <div class="item">餐券编号:<span>{{ detailInfo.code }}</span></div>
      <div v-if="/公务餐/.test(detailInfo.typeString)" class="item">使用数量:<span>{{ detailInfo.usePersonQty || 0 }}</span></div>
      <div v-if="/公务餐/.test(detailInfo.typeString)" class="item">申请理由:<span>{{ detailInfo.reason || '无' }}</span></div>
      <div v-if="/公务餐/.test(detailInfo.typeString)" class="item">申请备注:<span>{{ detailInfo.remark || '无' }}</span></div>
      <div class="item">餐券状态:<span>{{ /0/.test(detailInfo.isExpired) ? detailInfo.statusName : '已过期' }}</span></div>
      <a-table
        bordered
        class="s-table"
        :columns="mealColumns.filter(({ title }) => /公务餐/.test(detailInfo.typeString) ? '备注' !== title : true)"
        :data-source="detailInfo.mealLogVoList"
        :locale="{ emptyText: '暂无数据' }"
        :scroll="{ y: 400 }"
        :pagination="false"
        row-key="id"
      />
    </a-modal>

    <ExportModal
      items="订餐日期,餐券状态"
      :status-list="statusList"
      :show="showExport"
      :sending="sending"
      :default-params="exportParam"
      @ok="handleExport"
      @cancel="showExport = false"
      @show="bool => (showExport = bool)"
    />

  </page-view>
</template>

<script>
import { PageView, STable, ExportModal } from '@/components'
import { mapState } from 'vuex'

const getStatus = { 3: { true: 4, false: 5 }, 6: { true: 8, false: 7 }}
const statusTable = {
  '-1': '未支付',
  0: '未使用',
  1: '已使用',
  2: '已过期',
  3: '换餐中',
  4: '已换餐',
  5: '换餐失败',
  6: '申请中',
  7: '申请失败',
  8: '申请成功'
}
const type = {
  0: '普通餐',
  1: '公务餐'
}

export default {
  name: 'Manage',
  components: { PageView, STable, ExportModal },
  inject: ['formItemLayout'],

  data () {
    return {
      type,
      statusTable,
      statusList: ['全部'].concat(Object.values(statusTable)).map(label => ({ label, value: label === '全部' ? undefined : label })),

      exportParam: { status: undefined },
      queryParam: {
        createdByName: '',
        code: '',
        scheduleDate: this.$moment().format('YYYY-MM-DD'),
        typeId: undefined,
        status: undefined,
        pageSize: 10,
        pageNum: 1
      },

      selectedDay: this.$moment(),
      tempDate: this.$moment(),
      tempStatus: '全部',
      tempExportStatus: '全部',
      dateSection: [],

      manageCount: 0,
      sending: false,
      // 表头
      columns: [
        {
          title: '餐券编号',
          dataIndex: 'code',
          customCell: (record = {}) => {
            const { $get } = this
            Object.assign(record, {
              typeString: $get(type, `${record.type}`, '无'),
              statusName: /1/.test(record.isExpired) ? '已过期' : $get(statusTable, `${record.status}`, '无')
            })
          }
        },
        { title: '餐券类型', align: 'center', dataIndex: 'typeString', scopedSlots: { customRender: 'type' }},
        { title: '订餐人', align: 'center', dataIndex: 'createdByName' },
        { title: '餐券时间', align: 'center', dataIndex: 'typeName' },
        { title: '餐券数量', align: 'center', dataIndex: 'personQty' },
        { title: '餐券状态', align: 'center', dataIndex: 'statusName' },
        { title: '操作', align: 'center', width: '150px', scopedSlots: { customRender: 'action' }}
      ],
      mealColumns: [
        { title: '时间', align: 'center', dataIndex: 'time' },
        { title: '餐券状态', width: '20%', align: 'center', dataIndex: 'statusName' },
        { title: '操作者', width: '25%', align: 'center', dataIndex: 'createdByName' },
        { title: '备注', width: '25%', align: 'center', dataIndex: 'reason' }
        // { title: '餐券编号', align: 'center', dataIndex: 'code' }
      ],
      list: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const { queryParam, $axios, $notification, $moment, list, $get } = this
        const that = this
        const params = {}
        for (const key in queryParam) {
          const item = queryParam[key]
          if (item) {
            if (key === 'status') {
              if (/2/.test(item)) params.isExpired = 1
              else {
                params[key] = item
                params.isExpired = 0
              }
            } else params[key] = item
          }
        }
        params.scheduleDate = $moment(params.scheduleDate).format('YYYY-MM-DD')
        list.splice(0)

        return $axios.post('api/mealCoupon/query', params).then(res => {
          if (res.data.code !== '000000') return { data: [] }
          that.manageCount = res.data.data.count // 设置总数
          list.push(...$get(res, 'data.data.dataList', []))
          return { data: list }
        }).catch(e => {
          $notification.error({ message: '连接服务器超时' })
        })
      },
      showExport: false,
      showDetail: false,
      detailInfo: {},
      today: this.$moment().format('YYYY-MM-DD')
    }
  },

  computed: {
    ...mapState({
      mealType: state => state.meal.mealType
    })
  },

  watch: {
    $route: {
      handler (t) {
        if (t.name === 'meal-manage') this.init()
      },
      immediate: true
    },

    'mealType' () {
      this.$forceUpdate()
    },

    dateSection () {
      this.$forceUpdate()
    }
  },

  methods: {
    init () {
      const { dateSection, getDaysOfWeek, $moment, refresh } = this
      if (!dateSection.length) dateSection.splice(0, dateSection.length, ...getDaysOfWeek())
      this.today = $moment().format('YYYY-MM-DD')
      refresh()
    },

    /**
     * 选择日期变更
     * @param {$Moment} date moment日期
     * @param {String} dateString 年-周数, 2020-2周
     */
    onWeekChange (date, dateString) {
      this.tempDate = date
    },

    /**
     * 获取当前周的所有日期
     * @param {Number|String} weekNum 一年中第几周
     */
    getDaysOfWeek (weekNum) {
      const { $moment, selectedDay } = this
      weekNum = weekNum || selectedDay.week() || $moment().week()
      const year = $moment().year()
      const days = new Array(7).fill(0).map((i, k) => $moment().day(k + 1).year(year).week(weekNum).format('YYYY-MM-DD'))
      return days
    },

    handleSearch () {
      const { dateSection, getDaysOfWeek, tempDate, queryParam, $findkey, tempStatus } = this
      this.selectedDay = this.tempDate
      const scheduleDate = tempDate.format('YYYY-MM-DD')
      const status = $findkey(statusTable, v => v === tempStatus)
      Object.assign(queryParam, { scheduleDate, status })
      dateSection.splice(0, dateSection.length, ...getDaysOfWeek())
      this.$handlePage()
    },

    handlePage (p) {
      this.$handlePage(p)
    },

    refresh () {
      const { $refs, $get } = this
      const dom = $get($refs, 'manageTable', {})
      dom.refresh && dom.refresh()
    },

    reset () {
      const { queryParam, dateSection, getDaysOfWeek, $moment } = this
      const now = $moment()
      for (const key in queryParam) {
        if (key === 'pageNum') queryParam.pageNum = 1
        else if (key === 'pageSize') queryParam.pageSize = 10
        else if (key === 'scheduleDate') queryParam.scheduleDate = now.format('YYYY-MM-DD')
        else queryParam[key] = undefined
      }
      this.selectedDay = now
      this.tempDate = now
      this.tempStatus = undefined
      dateSection.splice(0, dateSection.length, ...getDaysOfWeek())
    },

    /**
     * 变更选择日期
     */
    changeDate (dateString) {
      const { queryParam, refresh, $moment } = this
      const scheduleDate = $moment(dateString)
      this.selectedDay = scheduleDate
      Object.assign(queryParam, { scheduleDate })
      refresh()
    },

    /**
     * 更新餐券状态
     */
    changeStatus ({ item, bool }) {
      const { $axios, refresh, $notification, $get } = this
      const { id, status } = item
      if (/-1/.test(id)) return false
      $axios.put(`api/mealCoupon/${id}`, { status: $get(getStatus, `${status}.${bool}`, status) }).then(res => {
        if (res.data.code === '000000') refresh()
        else $notification.error({ message: $get(res, 'data. mesg', '请稍后再试') })
      })
    },

    async showMealDetail ({ id = '' }) {
      const { $axios, $get, $message } = this
      if (!id) return false
      this.$toggleSending(1)
      const detailInfo = await $axios.get(`api/mealCoupon/${id}`).then(res => $get(res, 'data.data', {})).catch(e => ({}))
      if (!detailInfo.id) {
        this.$toggleSending()
        $message.destroy()
        $message.error('请稍后再试')
        return false
      }
      detailInfo.typeString = $get(type, detailInfo.type, '无')
      detailInfo.statusName = /1/.test(detailInfo.isExpired) ? '已过期' : $get(statusTable, detailInfo.status, '未知')
      // detailInfo.useQty = $get(detailInfo, 'qrCode', 'qrUse:0').match(/\"qrUse\"\:[\d]+/)[0].replace('\"qrUse\"\:', '')
      $get(detailInfo, 'mealLogVoList', []).forEach(logItem => {
        Object.assign(logItem, {
          time: logItem.updatedTime && this.$moment(logItem.updatedTime).format('YYYY-MM-DD HH:mm:ss') || '未知',
          statusName: /1/.test(logItem.isExpired) ? '已过期' : $get(statusTable, `${logItem.status}`, '无'),
          code: '/'
        })
      })
      Object.assign(this, { detailInfo, showDetail: true })
      this.$toggleSending()
    },

    clickExport () {
      const { dateSection, queryParam, $get, $moment } = this
      const minScheduleDate = dateSection[0]
      const maxScheduleDate = dateSection[dateSection.length - 1]
      const param = {}
      const status = $get(statusTable, queryParam.status)
      if (status) param.status = status
      if (minScheduleDate && maxScheduleDate) {
        Object.assign(param, {
          min: $moment(minScheduleDate).format('YYYY-MM-DD'),
          max: $moment(maxScheduleDate).format('YYYY-MM-DD')
        })
      }
      this.exportParam = param
      this.showExport = true
    },

    async handleExport (params) {
      const { exportParam, $findkey } = this
      let statusName = ''
      if (params.status) {
        statusName = params.status
        params.status = $findkey(statusTable, o => o === params.status)
      }
      const param = { ...exportParam, ...params }
      param.minScheduleDate = param.min
      delete param.min
      param.maxScheduleDate = param.max
      delete param.max
      const { minScheduleDate = '', maxScheduleDate = '' } = param
      const str = (minScheduleDate && maxScheduleDate) ? `${minScheduleDate}至${maxScheduleDate}` : '全部时间'
      const bool = await this.$exportFile({ url: 'api/mealCoupon/export', param, fileName: `餐券报表_${str}_${statusName || '全部状态'}` })
      if (bool) this.showExport = false
    }
  }
}
</script>

<style lang="less" scoped>
.date-section {
  .Flex;
  border:1px solid #ccc;
  margin-top: 24px;
  margin-bottom: 6px;

  >div {
    border-right: 1px solid #ccc;
    text-align: center;
    padding: 10px 0;
    width: 20%;
    cursor: pointer;

    .anticon {
      font-size: 22px;
    }
  }

  >div:nth-last-child(1) {
    .Flex;
    .Flex-col;
    border-right: none;
    color: @blue;
    width: 100px !important;
  }

  .active {
    box-shadow: 0 -2px  3px 1px @blue;
  }
}

.ant-modal-body {
  .item {
    margin-bottom: 20px;

    span {
      margin-left: 10px;
    }
  }
}

</style>
